﻿
using Newtonsoft.Json;
using SqlSugar;
using System.Reflection.Emit;


namespace Repository.Base
{
    public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class, new()
    {
        private readonly ISqlSugarClient _sqlSugarClient;

        public BaseRepository(ISqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
        }

        public async Task<int> AddAsync(TEntity entity)
        {
            return await _sqlSugarClient.Insertable(entity).ExecuteReturnIdentityAsync();
        }

        public async Task<int> DeleteAsync(TEntity entity)
        {
            return await _sqlSugarClient.Deleteable(entity).ExecuteCommandAsync();
        }

        public async Task<List<TEntity>> GetAllAsync()
        {
            return await _sqlSugarClient.Queryable<TEntity>().ToListAsync();
        }

        public Task<TEntity> GetByIdAsync(int id)
        {
            return _sqlSugarClient.Queryable<TEntity>().InSingleAsync(id);
        }

        public async Task<List<TEntity>> Query()
        {
            await Task.CompletedTask;
            var data = "[{\"Id\":18,\"userName\":\"张三11\"}]";
            return JsonConvert.DeserializeObject<List<TEntity>>(data) ?? new List<TEntity>();
        }

        public Task<int> UpdateAsync(TEntity entity)
        {
            return _sqlSugarClient.Updateable(entity).ExecuteCommandAsync();
        }
    }
}
